from views.base import BaseHandler
from db import db
import json
class ResourceHandler(BaseHandler):
    def get(self):
        rid = self.get_query_argument("rid")
        sql = "select * from resource where pid != 0"
        res = db.findAll(sql)
        data = [{"key":i["id"],"label":i["name"]} for i in res]
        sql1 = "select resourceid from role_resource where userid=%d"%int(rid)
        res1 = db.findAll(sql1)
        lst = []
        for i in res1:
            lst.append(i["resourceid"])
        self.finish({"code": 200,"data":data,"lst":lst})
    # 配置资源
    def post(self):
        data = json.loads(self.request.body)
        userid = int(data["userid"])
        resourceid = data["resourceid"]
        # print(resourceid)
        sql = "delete from role_resource where userid=%d"%userid
        db.add(sql)
        for i in resourceid:
            sql1 = "insert into role_resource(userid,resourceid) values (%d,%d)"%(userid,int(i))
            db.add(sql1)
        db.commit()
        self.write({"code": 200, "msg":"配置资源成功"})

# 添加资源
class SetResource(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        name = data["name"]
        pid = int(data["pid"])
        url = data["url"]
        sql = "insert into resource(name,pid,url,type ) values ('%s',%d,'%s',%d)"%(name,pid,url,1)
        db.add(sql)
        db.commit()
        self.write({"code": 200, "msg":"添加资源成功"})
    # 获取id!=0的分类   下拉框
    def get(self):
        sql = "select * from resource where pid = 0 and type=1"
        res = db.findAll(sql)
        self.finish({"code": 200, "msg":"获取资源成功","data":res})
